package com.ananjt.utils.config;

import com.ananjt.utils.context.CurrentUser;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * @Description: 字段属性设置
 * @Author: chenanhai
 * @Date: 2019年11月13日
 */
public class ModelMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = CurrentUser.getUserId();
        Date now = new Date();

        setInsertProp(metaObject, userId, now);
        setUpdateProp(metaObject, userId, now);

        Object deleteFlag = this.getFieldValByName("deleteFlag", metaObject);
        if (null == deleteFlag) {
            this.setFieldValByName("deleteFlag", "0", metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        String userId = CurrentUser.getUserId();
        Date now = new Date();
        setUpdateProp(metaObject, userId, now);

    }

    public void setInsertProp(MetaObject metaObject, String userId, Date now) {
        //SP 包标准属性状态
        Object createDate = this.getFieldValByName("createDate", metaObject);
        if (null == createDate) {
            /**
             * 设置实体属性setter进去的值，优先级要高于自动填充的值。
             * 如果实体没有设置该属性，就给默认值，防止entity的setter值被覆盖。
             */
            this.setFieldValByName("createDate", now, metaObject);
        }
        Object createBy = this.getFieldValByName("createBy", metaObject);
        if (null == createBy) {
            this.setFieldValByName("createBy", userId, metaObject);
        }
    }

    public void setUpdateProp(MetaObject metaObject, String userId, Date now) {
        Object updateDate = this.getFieldValByName("updateDate", metaObject);
        if (null == updateDate) {
            this.setFieldValByName("updateDate", now, metaObject);
        }
        Object updateBy = this.getFieldValByName("updateBy", metaObject);
        if (null == updateBy) {
            this.setFieldValByName("updateBy", userId, metaObject);
        }
    }


}
